package com.serkol.abmanager.controller.api;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.serkol.abmanager.bean.GridResult;
import com.serkol.abmanager.bean.Result;
import com.serkol.abmanager.config.ConstantHeader;
import com.serkol.abmanager.constant.ResultConstant;
import com.serkol.abmanager.entity.Automobiles;
import com.serkol.abmanager.entity.Departments;
import com.serkol.abmanager.entity.Goods;
import com.serkol.abmanager.entity.Users;
import com.serkol.abmanager.libraries.Utils;
import com.serkol.abmanager.service.DepartmentsService;
import com.serkol.abmanager.service.GoodsService;
import com.serkol.abmanager.service.UsersService;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@RequestMapping("api/goods")
@ResponseBody
public class GoodsApiController {

    @Autowired
    private GoodsService service;

    @Autowired
    private DepartmentsService departmentsService;

    @PostMapping("/findByList")
    public GridResult findByList(@RequestParam(name = "qrcode", defaultValue = "") String qrcode, @RequestParam(name = "type", defaultValue = "0") int type, @RequestParam(name = "status", defaultValue = "0") long status, @RequestParam(name = "groupId", defaultValue = "0") long groupId, @RequestParam(name = "page", defaultValue = "0") int page, @RequestParam(name = "pagesize", defaultValue = "10") int pagesize) {

        GridResult page1 = service.findByList(page, pagesize, qrcode, type, status, groupId);

        return page1;
    }

    @PostMapping("/findById")
    public Result findById(@RequestParam(name = "id", defaultValue = "0") long id) {
        if (id > 0) {
            Goods byId = service.getById(id);
            if (byId != null) {
                return Result.ok(byId);
            } else {
                return Result.failure(ResultConstant.EMPTIY);
            }
        } else {
            return Result.failure();
        }


    }

    @PostMapping("/findByStastica")
    public Result findByStastica(@RequestParam(name = "groupId", defaultValue = "0") long groupId, @RequestParam(name = "deptId", defaultValue = "0") long deptId, @RequestParam(name = "date", defaultValue = "") String date) {
        if (groupId > 0) {
            int[] types = {1, 2, 3, 4, 5, 6, 7};
            QueryWrapper<Departments> departmentsQueryWrapper = new QueryWrapper<>();
            departmentsQueryWrapper.lambda().eq(Departments::getGroupId, groupId);

            if (deptId > 0) {
                departmentsQueryWrapper.lambda().eq(Departments::getId, deptId);
            }

            List<Departments> list = departmentsService.list(departmentsQueryWrapper);
            Iterator<Departments> iterator = list.iterator();
            List<Map<String, Object>> mapList = new ArrayList<>();

            while (iterator.hasNext()) {
                Map<String, Object> dmap = new HashMap<>();
                Departments next = iterator.next();
                dmap.put("id", next.getId());
                dmap.put("name", next.getName());
                Map<Integer, Integer> dmaptype = new HashMap<>();
                for (int i = 0; i < types.length; i++) {
                    int type = types[i];
                    QueryWrapper<Goods> goodsQueryWrapper = new QueryWrapper<>();

                    if (date != null) {
                        String format = "%Y-%m-%d";
                        String[] split = date.split("-");
                        if (split.length == 2) {
                            format = "%Y-%m";
                        }
                        goodsQueryWrapper.lambda().eq(Goods::getType, type);
                        goodsQueryWrapper.lambda().eq(Goods::getDeptId, next.getId());
                        goodsQueryWrapper.apply("DATE_FORMAT(DATE,'" + format + "')='" + date + "'");

                    } else {
                        goodsQueryWrapper.lambda().eq(Goods::getType, type);
                        goodsQueryWrapper.lambda().eq(Goods::getDeptId, next.getId());
                    }

                    goodsQueryWrapper.select("IFNULL(SUM(WEIGHT),0) as total");
                    Map<String, Object> map = service.getMap(goodsQueryWrapper);
                    int total = Integer.parseInt(String.valueOf(map.get("total")));
                    dmaptype.put(type, total);

                }
                dmap.put("data", dmaptype);
                mapList.add(dmap);

            }

            return Result.ok(mapList);
        } else {
            return Result.failure();
        }


    }


    @PostMapping("/findByDelete")
    public Result findByDelete(@RequestParam(name = "id", defaultValue = "0") long id) {
        if (id > 0) {
            boolean b = service.removeById(id);
            if (b) {
                return Result.ok();
            } else {
                return Result.failure(ResultConstant.EMPTIY);
            }
        } else {
            return Result.failure();
        }


    }

    @PostMapping("/edit")
    public Result edit(@RequestParam(name = "id", defaultValue = "0") long id,
            /*   @RequestParam(name = "groupType", defaultValue = "0") int groupType,*/
                       @RequestParam(name = "weight", defaultValue = "") int weight,
                       @RequestParam(name = "groupId", defaultValue = "0") long groupId,
                       @RequestParam(name = "deptId", defaultValue = "0") long deptId,
                       @RequestParam(name = "type", defaultValue = "0") int type,
                       @RequestParam(name = "roleId", defaultValue = "0") long roleId) {

        Result result = new Result();
        if (weight > 0) {
            Goods goods = new Goods();
            goods.setDeptId(deptId);
            goods.setGroupId(groupId);
            goods.setType(type);

            goods.setStatus(roleId);
            goods.setUserId(ConstantHeader.getAdminToken().getUserId());
            goods.setUserName(ConstantHeader.getAdminToken().getName());
            goods.setDate(new Date());
            //  goods.setUserId(userId);
            goods.setWeight(weight);
            boolean flag = false;
            if (id > 0) {
                goods.setId(id);
                flag = service.updateById(goods);
            } else {
                String rfId = Utils.getRfId(goods);
                System.out.println("GGGGGGGGGGGGGGG:" + rfId);
                goods.setQrCode(rfId);
                flag = service.save(goods);
                result.setData(goods);
            }
            if (flag) {
                result.setStatus(ResultConstant.SUCSESS);
            } else {
                result.setStatus(ResultConstant.FAIL);
            }
        } else {
            result.setMsg("不能为空");
        }

        return result;

    }
}
